import React from 'react'
import { Upload, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

class Avatar extends React.Component {
    state = {
        params: null,
        loading: false,
    };

    validate = (file) => {
        const isJPG = file.type === 'image/jpeg',
            isJPEG = file.type === 'image/jpeg',
            isGIF = file.type === 'image/gif',
            isPNG = file.type === 'image/png',
            isLt2M = file.size / 1024 / 1024 < 1;
        if (!(isJPG || isJPEG || isPNG)) {
            message.error('只能上传JPG、JPEG、PNG格式的图片~');
            return false;
        } else if (!isLt2M) {
            message.error('图片超过1M限制，不允许上传~');
            return false;
        }
        return true;
    }

    handleChange = info => {
        if (this.validate(info.file)) {
            getBase64(info.file.originFileObj, imageUrl =>
                this.setState({
                    imageUrl,
                    // loading: false,
                }),
            );
        }
    };
    beforeUpload = file => { //上传前的验证
        //限制图片 格式、size、分辨率
        // return (isJPG || isJPEG || isPNG) && isLt2M;
    }

    doImgUpload = (options) => {
        const { onSuccess, onError, file, onProgress } = options;
        const reader = new FileReader();
        reader.readAsDataURL(file); // 读取图片文件
        reader.onload = (f) => {
            const params = {
                name: file.name,
                size: file.size,
                type: file.type,
                myBase64: f.target.result, // 把 本地图片的base64编码传给后台，调接口，生成图片的url
            };
            this.setState({
                params
            })

            this.props.setImgFile(params);
        };
    }

    render() {
        const { loading, imageUrl } = this.state;
        const uploadButton = ( //是否正在加载
            <div>
                {loading ? <LoadingOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );

        return (
            <>
                <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={this.beforeUpload}
                    customRequest={this.doImgUpload}
                    onChange={this.handleChange}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
            </>
        );
    }
}

export default Avatar;